//middleware/Auth.js
module.exports =options => { //options是为了以后扩展使用，一般中间件都写成带参返回的函数
  const jwt = require("jsonwebtoken");
  const assert = require("http-assert");
  const db = require("../dbConfig.js"); //引入数据库封装模块
  return async (req, res, next) => {
    const token = (req.headers.authorization || " ").split(" ").pop();//提取请求头中的token pop是将数组最后一个元素取出来
    assert(token, 401, '没有token，请先登录');
    let {userId}=jwt.verify(token, req.app.get('secret'), (err, authData) => {
      if(err) return ''; 
      else return authData;
    });
    assert(userId, 401, '无效的 token，请重新登录');
    let [{id}]=await db('select id  from user where id=?',[userId]);
    req.userId=id;
    assert(req.userId, 401, '没有此用户，请重新登录');
    if(req.baseUrl.indexOf('admin')!=-1){
      if(req.userId!='ht5dX14zczAyV1rnb2MzOT4Y') assert(false,403, '你没有权限访问此接口');
    }
    await next();  
  };
}
